package com.renfei.ffmpegproject.act;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.renfei.ffmpegproject.Player.MinePlayer;
import com.renfei.ffmpegproject.R;
import com.renfei.ffmpegproject.base.BaseActivity;
import com.renfei.ffmpegproject.bean.MineTimeInfo;
import com.renfei.ffmpegproject.listener.MineOnErrorListener;
import com.renfei.ffmpegproject.listener.MineOnLoadListener;
import com.renfei.ffmpegproject.listener.MineOnParparedListener;
import com.renfei.ffmpegproject.listener.MineOnTimeInfoListener;
import com.renfei.ffmpegproject.listener.MinePauseResumeListener;
import com.renfei.ffmpegproject.listener.MineValumeDBListener;
import com.renfei.ffmpegproject.listener.OnCompleteListener;
import com.renfei.ffmpegproject.listener.OnRecordTimeListener;
import com.renfei.ffmpegproject.util.MineLog;
import com.renfei.ffmpegproject.util.MuteEnum;
import com.renfei.ffmpegproject.util.TimeUtil;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DecodeAudioDataActivity extends BaseActivity {


    @BindView(R.id.tv_current_time)
    TextView tvCurrentTime;
    @BindView(R.id.tv_seek_bar)
    SeekBar tvSeekBar;
    @BindView(R.id.tv_total_time)
    TextView tvTotalTime;
    @BindView(R.id.seek_bar_layId)
    LinearLayout seekBarLayId;
    @BindView(R.id.tv_ffmpeg_log)
    TextView tvFfmpegLog;
    @BindView(R.id.tv_pause)
    TextView tvPause;
    @BindView(R.id.tv_resume)
    TextView tvResume;
    @BindView(R.id.tv_stop)
    TextView tvStop;
    @BindView(R.id.iv_last)
    ImageView ivLast;
    @BindView(R.id.iv_next)
    ImageView ivNext;
    @BindView(R.id.seekBarVolume)
    SeekBar seekBarVolume;
    @BindView(R.id.tv_current_Volume)
    TextView tvCurrentVolume;
    private MinePlayer minePlayer;
    private PlayTimeHandler playTimeHandler;


    private int position;
    private boolean isSeekBar = false;

    private List<File> fileList;
    private int currentMusicPosition = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_decode_audio_data;
    }

    @Override
    protected void initListener() {
        fileList = new ArrayList<>();

        new ReadMusicFileThread(new WeakReference<>(this)).start();


        minePlayer = new MinePlayer();
        minePlayer.setVolume(50);
        //设置音量进度条
        seekBarVolume.setProgress(50);
        minePlayer.setMute(MuteEnum.MUTE_CENTER);
        tvCurrentVolume.setText("音量:" + minePlayer.getVolume() + "%");


        playTimeHandler = new PlayTimeHandler(new WeakReference<>(DecodeAudioDataActivity.this));
        minePlayer.setMineOnParparedListener(new MineOnParparedListener() {
            @Override
            public void onParpared() {
                MineLog.e("准备状态,可以开始播放音乐了");
                minePlayer.start();
            }
        });
        minePlayer.setMineOnLoadListener(new MineOnLoadListener() {
            @Override
            public void onLoad(boolean load) {
                if (load) {
                    MineLog.e("onLoad 加载中");
                } else {
                    MineLog.e("onLoad 播放中");
                }

            }
        });

        minePlayer.setMinePauseResumeListener(new MinePauseResumeListener() {
            @Override
            public void onPause(boolean pause) {
                if (pause) {
                    MineLog.e("暂停。。。");
                } else {
                    MineLog.e("播放中");
                }
            }
        });
        minePlayer.setMineOnTimeInfoListener(new MineOnTimeInfoListener() {
            @Override
            public void onTimeInfo(MineTimeInfo timeInfo) {
                Message message = new Message();
                message.what = 0;
                message.obj = timeInfo;
                playTimeHandler.sendMessage(message);
            }
        });

        minePlayer.setMineOnErrorListener(new MineOnErrorListener() {
            @Override
            public void onError(int code, String msg) {
                MineLog.e("code :" + code + " msg :" + msg);
            }
        });

        minePlayer.setOnCompleteListener(new OnCompleteListener() {
            @Override
            public void onComplete() {
                MineLog.e("音乐播放完成");
            }
        });

        minePlayer.setMineValumeDBListener(new MineValumeDBListener() {
            @Override
            public void onDbValue(int db) {
//                MineLog.e("db = " + db);
            }
        });

        minePlayer.setOnRecordTimeListener(new OnRecordTimeListener() {
            @Override
            public void onRecordTime(int recordTime) {
//                MineLog.d("recordTime   ="+recordTime);
            }
        });
        tvSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (minePlayer.getDuration() > 0 && isSeekBar) {
                    position = minePlayer.getDuration() * progress / 100;

                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekBar = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isSeekBar = false;
                minePlayer.onSeek(position);
            }
        });

        seekBarVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                minePlayer.setVolume(i);
                tvCurrentVolume.setText("音量:" + i + "%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }


    @OnClick({R.id.tv_ffmpeg_log, R.id.tv_pause, R.id.tv_resume, R.id.tv_stop, R.id.iv_last,
            R.id.iv_next,
            R.id.btn_channel_left,
            R.id.btn_channel_right,
            R.id.btn_channel_center,
            R.id.btn_speed_01,
            R.id.btn_speed_02,
            R.id.btn_speed_03,
            R.id.btn_speed_04,
            R.id.btn_start_record,
            R.id.btn_stop_record,
            R.id.btn_stop_goon,
            R.id.btn_stop_pause

    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_ffmpeg_log:
                //                String filePath = BASE_PATH + "xjj.mp3";
//                String filePath = BASE_PATH + "大田后生仔.mp3";
                String filePath = "http://mpge.5nd.com/2015/2015-11-26/69708/1.mp3";
//                File file = new File(filePath);

//                if (!file.exists()) {
//                    showToast("文件不存在");
//                    return;
//                }
                minePlayer.setSource(filePath);
                minePlayer.parpared();
                break;
            case R.id.tv_pause:
                minePlayer.pause();
                break;
            case R.id.tv_resume:
                minePlayer.resume();
                break;
            case R.id.tv_stop:
                minePlayer.stop();
                break;
            case R.id.iv_last:
//                minePlayer.playNext(BASE_PATH + "xjj.mp3");

                if (null != fileList && fileList.size() > 0) {
                    if (currentMusicPosition > 1) {
                        currentMusicPosition -= 1;
                    } else {
                        currentMusicPosition = 0;
                    }
                    minePlayer.playNext(fileList.get(currentMusicPosition).getPath());
                } else {
                    showToast("暂无其他音乐文件");
                }

                break;
            case R.id.iv_next:
//                minePlayer.playNext(BASE_PATH + "大田后生仔.mp3");

                if (null != fileList && fileList.size() > 0) {
                    if (currentMusicPosition < fileList.size() - 1) {
                        currentMusicPosition += 1;
                    } else {
                        currentMusicPosition = 0;
                    }
                    minePlayer.playNext(fileList.get(currentMusicPosition).getPath());
                } else {
                    showToast("暂无其他音乐文件");
                }
                break;
            case R.id.btn_channel_left:
                minePlayer.setMute(MuteEnum.MUTE_LEFT);
                break;
            case R.id.btn_channel_right:
                minePlayer.setMute(MuteEnum.MUTE_RIGHT);
                break;
            case R.id.btn_channel_center:
                minePlayer.setMute(MuteEnum.MUTE_CENTER);
                break;
            case R.id.btn_speed_01://变速不变调
                minePlayer.setPtitch(1.0f);
                minePlayer.setSpeed(1.5f);
                break;
            case R.id.btn_speed_02://变调不变速
                minePlayer.setPtitch(1.5f);
                minePlayer.setSpeed(1.0f);
                break;
            case R.id.btn_speed_03://变速又变调
                minePlayer.setPtitch(1.5f);
                minePlayer.setSpeed(1.5f);
                break;
            case R.id.btn_speed_04://正常
                minePlayer.setPtitch(1.0f);
                minePlayer.setSpeed(1.0f);
                break;

            case R.id.btn_start_record:

                String parentPath = Environment.getExternalStorageDirectory().getPath();

                loge("parentPath", parentPath);

                File file = new File(parentPath + "/testplayer.aac");

                minePlayer.startRecord(file);
                break;
            case R.id.btn_stop_goon:
                minePlayer.resumeRecord();
                break;
            case R.id.btn_stop_pause:
                minePlayer.pauseRecord();
                break;
            case R.id.btn_stop_record:
                minePlayer.stopRecord();
                break;
        }
    }


    static class PlayTimeHandler extends Handler {
        private WeakReference<DecodeAudioDataActivity> weakReference;

        public PlayTimeHandler(WeakReference<DecodeAudioDataActivity> weakReference) {
            this.weakReference = weakReference;
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    MineTimeInfo timeInfo = (MineTimeInfo) msg.obj;
                    if (null != weakReference.get() && !weakReference.get().isSeekBar) {

                        if (null != weakReference.get().tvCurrentTime
                        ) {
                            weakReference.get().tvCurrentTime.setText(TimeUtil.secdsToDateFormat(timeInfo.getCurrentTime()));
                        }
                        if (null != weakReference.get().tvCurrentTime) {
                            weakReference.get().tvTotalTime.setText(TimeUtil.secdsToDateFormat(timeInfo.getTotalTime()));
                        }
                        if (null != weakReference.get().tvSeekBar) {
                            weakReference.get().tvSeekBar.setProgress(
                                    timeInfo.getCurrentTime() * 100 / timeInfo.getTotalTime()

                            );
                        }
                    }
                    break;
            }

        }
    }


    static class ReadMusicFileThread extends Thread {
        private WeakReference<DecodeAudioDataActivity> weakReference;

        public ReadMusicFileThread(WeakReference<DecodeAudioDataActivity> weakReference) {
            this.weakReference = weakReference;
        }

        @Override
        public void run() {
            super.run();
            Directory_traversal(Environment.getExternalStorageDirectory().getPath(), getFileNameEndRule());

            Log.e("ReadMusicFileThread", "run: " + weakReference.get().fileList.size() + "");
        }


        private void Directory_traversal(String path, String[] ser) {//path为目录
            File file = new File(path);
            File[] files = file.listFiles();//遍历该目录所有文件和文件夹对象

            for (int i = 0; i < files.length; i++) {
                String str = files[i].toString();//类型转换String
                //判断files是否为一个目录
                if (files[i].isDirectory()) {
                    //递归操作，逐一遍历各文件夹内的文件
                    Directory_traversal(str, ser);
                } else {
                    if (!files[i].isDirectory()) {
                        for (String s : ser) {
                            if (files[i].getName().endsWith(s)) {
                                weakReference.get().fileList.add(files[i]);
                            }
                        }
                    }
                }
            }
        }

        public String[] getFileNameEndRule() {
            return new String[]{
                    ".arm", ".wav", ".aac", ".mp3", ".m4a"
            };
        }
    }


}
